package com.singerw.service.security;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.singerw.mapper.TwCollegeMapper;
import com.singerw.pojo.TwCollege;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @version V1.0
 * @Package com.singerw.service.security
 * @auhter 张欣
 * @date 2021/1/30-3:46 PM
 */

@Service
public class TwCollegeService {

    @Resource
    private TwCollegeMapper twCollegeMapper;

    public List<TwCollege> list(){
        return twCollegeMapper.selectList(null);
    }

    public List<TwCollege> findByCollegeName(String collegeName){
        QueryWrapper<TwCollege> wrapper = new QueryWrapper<>();
        wrapper.eq("college_name",collegeName);
       return twCollegeMapper.selectList(wrapper);
    }

    /**
     * 判断此用户是否拥有此部门的权限
     * @param userName
     */
    public boolean findByUserNameIsAdmin(String collegeName, String userName){
        List<TwCollege> twColleges = findByCollegeName(collegeName);
        if(twColleges.size() > 0){
            TwCollege twCollege = twColleges.get(0);
            JSONArray objects = JSON.parseArray(twCollege.getAdministrators());
            return objects.contains(userName);
        }
        return false;
    }

    public boolean isExistence(String collegeName){
        System.out.println("isExistence");
        if(findByCollegeName(collegeName).size() == 0){
            System.out.println("isExistence 1");
            TwCollege twCollege = new TwCollege();
            twCollege.setCollegeName(collegeName);
            twCollege.setAdministrators(new JSONArray().toJSONString());
            save(twCollege);
            return false;
        }
        return true;
    }

    public void save(TwCollege twCollege) {
        if (twCollege.getId() == null) {
            twCollegeMapper.insert(twCollege);
            return;
        }
        twCollegeMapper.updateById(twCollege);
    }
}
